<?php


class CustomerService extends TP_Service {
    private $role;
    public function __construct() {
        parent::__construct();
        $this->load->model("SModel/Customer_model");
        $this->load->model("SModel/Staff_model");
        $this->load->model("SModel/Account_model");
        $this->load->model("PModel/V_admin_model");
        $this->load->service("PService/AccountService");
        $this->load->service("PService/UploadService");
        $this->load->service("PService/ExportExcelService");
        $this->role = $this->getRole($_SESSION[SESS_UUID]);
    }


    // 能否操作
    private function hasPre() {
        if ($this->role->role_id != WebRole::Manage[TPEnum::Value]) {
            exit(retJson(ErrCode::ErrCode_10404));
        }
    }



    /**
     * 方法名 customerList
     *
     * @Name 获取方法列和角色方法列
     * @Desc 客户列表
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一e
     * @return      [type]                   [description]
     */
    public function customerList($param, $export = false) {
        if (!$export) {
            $param = array_filter($param, 'filtrfunction');
            if (!isset($param['pageNo'], $param['pageSize'])) {
                exit(retJson(ErrCode::ErrCode_10002));
            }

            $conarr['pageNo'] = $param['pageNo'];
            $conarr['pageSize'] = $param['pageSize'];
        }


        $conarr['items'] = "a.id, usercode, username, email, mobile, company, position, region, country, valid, ascription, ascription_name, sales_area, privilege_level";
        $conarr['join']  = array("tp_v_admin a", 'tp_customer.aid = a.id');
        $conarr['orderby'] = "id asc";
        $conarr['where']   = "1 = 1";



        if(isset($param['input']) && !empty($param['input'])){
            $conarr['where'] .= sql_format(" AND ( usercode like '%{0}%' OR  username like '%{0}%' OR email like '%{0}%' )", $param['input']);
        }


        if ($export) {
            $list = $this->Customer_model->get_list_full($conarr);
        } else {
            $list = $this->Customer_model->get_page_list($conarr);
            foreach ($list['ret'] as &$value) {
                $value['validInfo'] = $value['valid'] == EnableState::Enable[TPEnum::Value] ? "已启用" : "已停用";

                $value['sales_area'] = json_decode($value['sales_area'], true) ?? [];
                $areas = array_column($value['sales_area'], 1) ?? [];
                $value['areaInfo'] = implode("、", $areas);

                $value['levelInfo']       = $value['privilege_level'];
                $value['privilege_level'] = explode("、", $value['privilege_level']);
            }
        }
        return $list;
    }




    /**
     * 方法名 customerEdit
     *
     * @Name 获取方法列和角色方法列
     * @Desc 客户修改
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     *
     */
    public function customerEdit($param) {
        if (!isset(
            $param['usercode'],
            $param['username'],
            $param['country'],
            $param['region'],
            $param['position'],
            $param['privilege_level'],
            $param['sales_area'],
            $param['email'],
            $param['company'],
            $param['ascription'],
        ) || !is_array($param['sales_area']) || !is_array($param['privilege_level'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }

        $this->hasPre();

        if (!filter_var($param['email'], FILTER_VALIDATE_EMAIL)) {
            exit(retJson(ErrCode::ErrCode_10504));
        }
        // if (!validMobile($param['mobile'])) {
        //     exit(retJson(ErrCode::ErrCode_10505));
        // }



         // 终端销售区域数据
         $areas = '';
         foreach ($param['sales_area'] as $value) {
             if (count($value) == 1) {
                 $father[$value[0]] = $value[0];
                 $areas .= "$value[0],";
             } else {
                 $children[] = $value;
             }
         }
         if (isset($children)) {
             foreach ($children as $value) {
                 if (count($value) == 2) {
                     if (!isset($father[$value[0]])) {
                         $father[$value[1]] = $value[1];
                         $areas .= "$value[1],";
                     }
                 } else {
                     $childrenF[] = $value;
                 }
             }
         }
         if (isset($childrenF)) {
            foreach ($childrenF as $value) {

                if (count($value) == 3) {

                    if (!isset($father[$value[0]]) && !isset($father[$value[1]])) {
                        $areas .= "$value[2],";
                    }
                }else{
                    if (!isset($father[$value[0]]) && !isset($father[$value[1]]) && !isset($father[$value[2]])) {
                        $areas .= "$value[3],";
                    }
                }
            }
        }
         $areas = rtrim($areas, ',');

        $sales_area = json_encode($param['sales_area'], JSON_UNESCAPED_UNICODE);
        $privilege_level = implode("、", $param['privilege_level']);

        if (empty($param['id'])) {
            // 新增账户
            $p = ['usercode' => $param['usercode'], 'username' => $param['username'], 'role_id' => [WebRole::Customer[TPEnum::Value]],'email' => $param['email'], 'uuid' => ''];
            $param['id'] = $this->AccountService->saveAdminInfo($p);

            $this->Customer_model->add(['aid' => $param['id']]);
        }

        $sql = sql_format(
            "UPDATE tp_customer c JOIN tp_account a ON c.aid = a.id SET
                username = '{0}', email = '{1}', mobile = '{2}', country = '{3}', region = '{4}',position = '{5}',privilege_level = '{6}',
                sales_area = '{7}', areas = '{8}', company = '{9}', ascription = '{10}', ascription_name = '{11}', account_type = '{12}' ,c.othermobile = '{13}'
            WHERE a.id = '{13}'",
            $param['username'],
            $param['email'],
            $param['mobile'] ?? '',

            $param['country'],
            $param['region'],
            $param['position'],
            $privilege_level,
            $sales_area,
            $areas,
            $param['company'],
            $param['ascription'],
            $param['ascription_name'],
            AccountType::Cust[TPEnum::Value],
            $param['id'],
            $param['otherMobile'] ?? ''
        );
        $this->Customer_model->execute($sql);
        return true;
    }




    /**
     * 方法名 customerDelete
     *
     * @Name 获取方法列和角色方法列
     * @Desc 客户删除
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一
     * @return      [type]                   [description]
     *
     */
    public function customerDelete($param) {
        if (!isset($param['aid']) || empty($param['aid'])) {
            exit(retJson(ErrCode::ErrCode_10002));
        }


        $this->Customer_model->delete(['aid' => $param['aid']]);
        $this->Account_model->delete(['id' => $param['aid']]);
        return true;
    }




    /**
     * 方法名 customerImport
     *
     * @Name dealStock
     * @Desc 客户导入
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2022-02-17 14:11:28
     * @return      [type]                   [description]
     */
    public function customerImport($db) {
        $this->hasPre();

        if (empty($_FILES)) {
            exit(retJson(ErrCode::ErrCode_10601));
        }


        $path = $this->UploadService->UploadFile('studentSource', true);
        $excellist =  $this->ExportExcelService->importexcel($path, 'M', 'A', 2);
        if (count($excellist) == 0) {
            exit(retJson(ErrCode::ErrCode_10602));
        }

        //去掉空数组
        foreach ($excellist as $k =>  &$value) {
            // $value = array_filter($value, 'filtrfunction');
            foreach(explode(',', $value['K']) as $v3){
                if(!empty($v3) && !in_array($v3,["100","1000","2000","3000","4000","5000","6000"])){
                    exit($this->retJson("第" . ($k + 1) . "行", ErrCode::ErrCode_10907));
                }
            } 

            if(empty($value['C'])){
                unset($excellist[$k]);
            }
        }

		$db->trans_begin();

        foreach ($excellist as $index => $v) {
            $plate = [];
            if (!empty($v['K'])) {
                $continent = explode(',', $v['K']);
                foreach ($continent as $key => $value) {

                    if ($value == 100) {
                        $plate[] = [$value];
                    } else {
                        $plate[] = ["100", $value];
                    }
                }
            }

            if (!empty($v['L'])) {
                $p = explode(',', $v['L']);

				unset($value);
				foreach ($p as $key => $value) {
                    $father = substr($value, 0, 1) * 1000;
                    $plate[] = [
                        "100", "$father", "$value"
                    ];
                }


            }

            if (!empty($v['M'])) {
                $p = explode(',', $v['M']);
                unset($value);
                foreach ($p as $key => $value) {
                    $plate[] = [
                        "100", "1000","1001", "$value"
                    ];
                }
            }

            $areas = '';

            $children = [];
            $childrenF = [];
            $fathers = [];

            foreach ($plate as $value) {
                if (count($value) == 1) {
                    $fathers[$value[0]] = $value[0];
                    $areas .= "$value[0],";
                } else {
                    $children[] = $value;
                }
            }
            if (!empty($children)) {
                foreach ($children as $value) {
                    if (count($value) == 2) {
                        if (!isset($fathers[$value[0]])) {
                            $fathers[$value[1]] = $value[1];
                            $areas .= "$value[1],";
                        }
                    } else {
                        $childrenF[] = $value;
                    }
                }
            }


            if (!empty($childrenF)) {
                foreach ($childrenF as $value) {
                    if (count($value) == 3) {
                        if (!isset($fathers[$value[0]]) && !isset($fathers[$value[1]])) {
                            $areas .= "$value[2],";
                        }
                    }else{
                        if (!isset($fathers[$value[0]]) && !isset($fathers[$value[1]]) && !isset($fathers[$value[2]])) {
                            $areas .= "$value[3],";
                        }
                    }
                }
            }
            $areas = rtrim($areas, ',');

            if ($v['F'] == '' || $v['F'] == null) {
				exit($this->retJson('第' . ($index + 1) . '行归属业务员账号不能为空,', ErrCode::ErrCode_10003));
			}


            $p = ['usercode' => $v['A'], 'username' => $v['B'], 'role_id' => [WebRole::Customer[TPEnum::Value]], 'uuid' => '','email' => $v['C']];
            $aid = $this->AccountService->saveAdminInfo($p);


//            $sql = sql_format(
//                "UPDATE tp_customer c JOIN tp_account a ON c.aid = a.id SET
//                    email = '{0}', mobile = '{1}', country = '{2}', region = '{3}', company = '{4}', position = '{5}', account_type = '{6}',sales_area = '{8}' ,areas = '{9}'
//                WHERE a.id = '{7}'",
//                $v['C'],
//                $v['D'],
//                $v['E'],
//                $v['F'],
//                $v['G'],
//                $v['H'],
//                AccountType::Cust[TPEnum::Value],
//                $aid,
//                json_encode($plate, JSON_UNESCAPED_UNICODE),
//                $areas
//            );

			// 获取业务员账号ID
			$t_account = $this->Account_model->get_single(array('usercode'=>$v['F']));
			$t_id = $t_account['id'];

			if (!$t_id) {
//				$this->Account_model->delete(['id' => $aid], true);
				$db->trans_rollback();
				exit($this->retJson('第' . ($index + 1) . '行归属业务员账号 ' . $v['F'] . ' 不存在,', ErrCode::ErrCode_10003));
			}

			$this->Customer_model->add(['aid' => $aid]);

            $sql = sql_format(
                "UPDATE tp_customer c JOIN tp_account a ON c.aid = a.id SET
                    email = '{0}', mobile = '{1}', country = '{2}', region = '{3}', company = '{4}', `position` = '{5}', account_type = '{6}',sales_area = '{8}' ,areas = '{9}',ascription_name = '{10}', ascription = '{11}'
                WHERE a.id = '{7}'",
                $v['C'],
                $v['I'],
                $v['D'],
                $v['E'],
                $v['H'],
                $v['J'],
                AccountType::Cust[TPEnum::Value],
                $aid,
                json_encode($plate, JSON_UNESCAPED_UNICODE),
                $areas,
				$t_account['username'],
				$t_id
            );
            $this->Customer_model->execute($sql);
        }

		$db->trans_commit();
        return true;
    }




    /**
     * 方法名 searchCustomer
     *
     * @Name 获取方法列和角色方法列
     * @Desc 查找客户
     * @OpenFlag 是否开放,1开放0权限控制
     * @Author      zn
     * @Date 2021-11-15 09:30:37 星期一e
     * @return      [type]                   [description]
     */
    public function searchCustomer($param) {
        // $param = array_filter($param, 'filtrfunction');
        // if (!isset($param['username'])) {
        //     exit(retJson(ErrCode::ErrCode_10002));
        // }

        $conarr['items'] = "tp_v_admin.id, tp_v_admin.username, tp_v_admin.usercode";
        $conarr['join'] = array("tp_customer c","c.aid = tp_v_admin.id");
        $conarr['where'] = sql_format("tp_v_admin.role_id = '{0}'  ", WebRole::Customer[TPEnum::Value]);

        if($this->role->role_id == WebRole::Salesman[TPEnum::Value]){
            $conarr['where'] .= sql_format(" AND (c.ascription = '{0}' OR ascription = '{1}')", $this->role->id, 0);
        }

        if($this->role->role_id == WebRole::BusinessS[TPEnum::Value]){
            $con['items'] = "aid";
            $con['where'] = sql_format(" ascription = '{0}'",$this->role->id);
            $sale = $this->Staff_model->get_list_full($con);

//            if(empty($sale)){
//                return [];
//            }

            $arr = [];
            foreach ($sale as $key => $value) {
                $arr[] = $value['aid'];
            }


            $arr[] = 0;

            $aids = implode(",",$arr);
            $conarr['where'] .= sql_format(" AND c.ascription in ({0})", $aids);
        }

        if (isset($param['username'])) {
			$conarr['where'] = sql_format("role_id = '{0}' and username like '{1}%'", WebRole::Customer[TPEnum::Value], $param['username']);
		}

        $list = $this->V_admin_model->get_list_full($conarr);

        return $list;
    }



    
    /**
     * @Desc     返回值-Controller返回页面去
     * @Author   pekey
     * @DateTime 2020-05-12T19:25:48+0800
     * @param    errorCode,错误代码枚举，包含错误代码，及错误信息
     * @param    boolean，返回是否正确
     * @param    array，数据
     * @param    array，其他数据
     * @return   [type]，返回json类型
     */
    function retJson($desc, $errorCode, $data = array(), $append = array()) {
        $ret = array();

        $ret[RET_CODE]   = $errorCode[TPEnum::Value];
        $ret[RET_MSG]    = $desc . $errorCode[TPEnum::Caption];
        $ret[RET_EN_MSG] = $errorCode[TPEnum::Append1];
        $ret[RET_STATUS] = checkRetStatus($errorCode);

        if (is_array($data)) {
            $ret[RET_DATA] = json_encode($data);
        } else {
            $ret[RET_DATA] = $data;
        }
        if (is_array($append)) {
            $ret[RET_APPEND] = json_encode($append);
        } else {
            $ret[RET_APPEND] = $append;
        }

        return json_encode($ret);
    }
}
